package com.xh.utils;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Objects;

/**
 * @Name RequestUtil
 * @Description
 * @Author wen
 * @Date 2019-07-11
 */
@Slf4j
public class RequestUtil {

    /**
     * 获取用户真实IP地址，不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值
     */
    private static final String UNKNOWN = "unknown";

    private static final String LOCAL_IP_ADDRESS = "127.0.0.1";

    private static final String IP_ADDRESS = "0:0:0:0:0:0:0:1";

    private static final int IP_ADDRESS_LENGTH = 15;

    private static final String SPLIT = ",";

    /**
     * 获取用户真实ip
     */
    public static String getIpAddress(HttpServletRequest request) {
        if (Objects.isNull(request)) {
            return UNKNOWN;
        }
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();

            if (LOCAL_IP_ADDRESS.equals(ipAddress) || IP_ADDRESS.equals(ipAddress)) {
                // 根据网卡获取本机配置的IP地址
                InetAddress inetAddress;
                try {
                    inetAddress = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    throw new IllegalArgumentException("获取IP失败");
                }
                ipAddress = inetAddress.getHostAddress();
            }
        }

        // 对于通过多个代理的情况，第一个IP为客户端真实的IP地址，多个IP按照','分割
        if (null != ipAddress && ipAddress.length() > IP_ADDRESS_LENGTH) {
            // "***.***.***.***".length() = 15
            if (ipAddress.indexOf(SPLIT) > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }

        return ipAddress;
    }

    /**
     * @param request
     * @return boolean
     * @Name isAjaxRequest
     * @Description 判断是否为Ajax请求
     * @Author wen
     * @Date 2019/7/11
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equals(header);
    }

}
